<?php

class UsuarioController extends Controller
{
	public $layout='//layouts/column1';

	public function filters()
	{
		return array(
			//'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}
	
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('cadastro'),
				'users'=>array('*'),
			),
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('atualizar'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('alterarSenha'),
				'users'=>array('*'),
			),
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index'),
				'users'=>array('*'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionCadastro()
	{
		if (!Yii::app()->user->isGuest)
			$this->redirect(array('atualizar'));
		
		$model=new Usuario;
		$model->unsetAttributes();
		
		if(isset($_POST['Usuario']))
		{
			$model->attributes=$_POST['Usuario'];
			if($model->save())
				$this->redirect(array('index'));
		}
		$this->render('cadastro',array(
			'model'=>$model,
		));
	}
	
	public function actionAtualizar()
	{
		$model=$this->loadModel();
		$model->senhaNova = $model->senhaNova2 = $model->senhaAntiga = $model->senha;
		$model->scenario = 'atualizar';
		if(isset($_POST['Usuario']))
		{
			$model->attributes = $_POST['Usuario'];
			$model->nascimento = $_POST['Usuario']['nascimento'];
			if($model->update()) {
				Yii::app()->user->setFlash('success','Dados atualizados!');
				$this->redirect(array('atualizar'));
			}
		}
		$this->render('atualizar',array(
			'model'=>$model,
		));
	}
	
	public function actionAlterarSenha()
	{
		$model=new Usuario;
		$model->unsetAttributes();
		$model=$this->loadModel();
		$model->senhaAntiga = $model->senha;
		$model->senha = '';
		if(isset($_POST['Usuario']))
		{
			$model->attributes=$_POST['Usuario'];
			if($model->validate()) {
				$model->senha = $model->senhaNova;
				$model->update();
				Yii::app()->user->setFlash('success','Dados atualizados!');
				$this->redirect(array('atualizar'));
			}
		}
		$this->render('alterarSenha',array(
			'model'=>$model,
		));
	}
	
	public function actionIndex()
	{
		$this->render('index',array(
			'model'=>$this->loadModel(),
		));
	}
	
	public function loadModel()
	{
		$model=Usuario::model()->findByPk(Usuario::getUsuario()->id_usuario);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='usuario-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
}